package com.tool;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * *********************************************
 * @author Administrator
 * @FileName PropertiesUtil.java
 * @Description properties工具类
 **********************************************
 */
public class PropertiesUtil {
	public static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class);
	
	/**
	 * 读配置文件
	 * @param fileName
	 * @return
	 */
	public static Properties readPropertiesAsStream(String fileName){
		Properties properties = new Properties();
		InputStreamReader in = null;
		try {
			in = new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8");
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return properties;
	}
	
	/**
	 * 读配置文件
	 * @param fileName
	 * @return
	 */
	public static Properties readProperties(String fileName){
		Properties properties = new Properties();
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(fileName));
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return properties;
	}
	
	/**
	 * 修改配置文件
	 * @param props
	 * @param keyname
	 * @param keyvalue
	 */
	public static void writeProperties(String fileName ,String keyname,String keyvalue) {    
		Properties props = readProperties(fileName);
		OutputStream fos = null;
        try {   
        	fos = new FileOutputStream(fileName);   
            props.setProperty(keyname, keyvalue);   
            LOG.info(new StringBuilder().append("keyname:").append(keyname).append("==keyvalue:").append(keyvalue).toString());
            props.store(fos, "Update '" + keyname + "' value '" + keyvalue + "'");   
        } catch (IOException e) {   
        	e.printStackTrace();  
        } finally {
        	try{
        		if(fos != null){
        			fos.close();
        		}
        	}catch(IOException e){
        		e.printStackTrace();
        	}
        }
    } 
	
	public static String getValue(Properties prop,String key){
		return prop.getProperty(key);
	}

}
